package dr.common.i18n;

import cn.hutool.core.util.StrUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.i18n.FixedLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 * 自定义解析器，解析http请求中的language信息
 * @author 450216797@qq.com
 */
public class ResKitLocalResolver implements LocaleResolver {

    private Locale defaultLocale;

    public void setDefaultLocale(Locale defaultLocale) {
        this.defaultLocale = defaultLocale;
    }

    public Locale getDefaultLocale() {
        return this.defaultLocale;
    }

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Locale defaultLocale = this.getDefaultLocale();
        //获取application.properties默认的配置
        if(defaultLocale != null && request.getHeader("Accept-Language") == null) {
            return defaultLocale;
            //http请求头没获取到Accept-Language才采用默认配置
        } else {
            //request.getHeader("Accept-Language")获取得到的情况
            Locale requestLocale = request.getLocale();
            //获取request.getHeader("Accept-Language")的值
            String localeFlag = request.getHeader("ZS-Language");
            if(StrUtil.isEmpty(localeFlag)){
                localeFlag = request.getParameter("ZS-Language");
            }
            //从URL获取的locale值
            //url链接有传locale参数的情况，eg:zh_CN
            if (!StringUtils.isEmpty(localeFlag)) {
                String[] split = localeFlag.split("_");
                requestLocale = new Locale(split[0], split[1]);
            }
            //没传的情况，默认返回request.getHeader("Accept-Language")的值
            return requestLocale;
        }
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}